<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Email Handler | Monkeytype</title>
    <!-- <link rel="stylesheet" href="css/fa.css" /> -->
    <style>
      @import "balloon-css/balloon.min.css";
    </style>
    <link rel="stylesheet" href="themes/serika_dark.css" id="currentTheme" />
    <link id="favicon" rel="shortcut icon" href="images/fav.png" />
    <link rel="shortcut icon" href="images/fav.png" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
      integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    />
    <link rel="stylesheet" href="styles/index.scss" />
    <meta name="name" content="Monkeytype" />
    <meta name="image" content="https://monkeytype.com/mtsocial.png" />
    <meta
      name="description"
      content="The most customizable typing test website with a minimal design and a ton of features. Test yourself in various modes, track your progress and improve your speed."
    />
    <meta
      name="keywords"
      content="typing, test, typing-test, typing test, monkey-type, monkeytype, monkey type, monkey-types, monkeytypes, monkey types, types, monkey, type, miodec, wpm, words per minute, typing website, minimalistic, custom typing test, customizable, customisable, themes, random words, smooth caret, smooth, new, new typing site, new typing website, minimalist typing website, minimalistic typing website, minimalist typing test"
    />
    <meta name="author" content="Miodec" />
    <meta property="og:title" content="Email Handler | Monkeytype" />
    <meta property="og:url" content="https://monkeytype.com/" />
    <meta property="og:type" content="website" />
    <meta
      property="og:description"
      content="The most customizable typing test website with a minimal design and a ton of features. Test yourself in various modes, track your progress and improve your speed."
    />
    <meta property="og:image" content="https://monkeytype.com/mtsocial.png" />
    <meta name="theme-color" content="#e2b714" id="metaThemeColor" />
    <meta name="twitter:title" content="Email Handler | Monkeytype" />
    <meta name="twitter:image" content="https://monkeytype.com/mtsocial.png" />
    <meta name="twitter:card" content="summary_large_image" />
    <style>
      header {
        font-size: 2.5rem;
      }

      main {
        color: var(--text-color);
        display: grid;
        justify-content: center;
      }

      h1 {
        font-weight: unset;
        color: var(--main-color);
        font-size: 2rem;
        margin-top: 3rem;
      }

      body {
        justify-content: center;
        display: flex;
      }

      .preloader {
        text-align: center;
        display: grid;
        align-items: center;
        align-content: center;
        width: 350px;
        gap: 1rem;
      }
      .preloader .icon {
        font-size: 2rem;
        color: var(--main-color);
      }
      .preloader .subText {
        font-size: 1rem;
        color: var(--sub-color);
        font-style: italic;
      }

      .resetPassword {
        display: grid;
        width: 300px;
        gap: 1rem;
        align-items: center;
        align-content: center;
      }

      .hidden {
        display: none;
      }
    </style>
  </head>

  <body>
    <div id="app" class="content-grid">
      <header>
        <div id="logo">
          <div class="icon">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              xmlns:xlink="http://www.w3.org/1999/xlink"
              style="isolation: isolate"
              viewBox="-680 -1030 300 180"
            >
              <g>
                <path
                  d="M -430 -910 L -430 -910 C -424.481 -910 -420 -905.519 -420 -900 L -420 -900 C -420 -894.481 -424.481 -890 -430 -890 L -430 -890 C -435.519 -890 -440 -894.481 -440 -900 L -440 -900 C -440 -905.519 -435.519 -910 -430 -910 Z"
                />
                <path
                  d=" M -570 -910 L -510 -910 C -504.481 -910 -500 -905.519 -500 -900 L -500 -900 C -500 -894.481 -504.481 -890 -510 -890 L -570 -890 C -575.519 -890 -580 -894.481 -580 -900 L -580 -900 C -580 -905.519 -575.519 -910 -570 -910 Z "
                />
                <path
                  d="M -590 -970 L -590 -970 C -584.481 -970 -580 -965.519 -580 -960 L -580 -940 C -580 -934.481 -584.481 -930 -590 -930 L -590 -930 C -595.519 -930 -600 -934.481 -600 -940 L -600 -960 C -600 -965.519 -595.519 -970 -590 -970 Z"
                />
                <path
                  d=" M -639.991 -960.515 C -639.72 -976.836 -626.385 -990 -610 -990 L -610 -990 C -602.32 -990 -595.31 -987.108 -590 -982.355 C -584.69 -987.108 -577.68 -990 -570 -990 L -570 -990 C -553.615 -990 -540.28 -976.836 -540.009 -960.515 C -540.001 -960.345 -540 -960.172 -540 -960 L -540 -960 L -540 -940 C -540 -934.481 -544.481 -930 -550 -930 L -550 -930 C -555.519 -930 -560 -934.481 -560 -940 L -560 -960 L -560 -960 C -560 -965.519 -564.481 -970 -570 -970 C -575.519 -970 -580 -965.519 -580 -960 L -580 -960 L -580 -960 L -580 -940 C -580 -934.481 -584.481 -930 -590 -930 L -590 -930 C -595.519 -930 -600 -934.481 -600 -940 L -600 -960 L -600 -960 L -600 -960 L -600 -960 L -600 -960 L -600 -960 L -600 -960 L -600 -960 C -600 -965.519 -604.481 -970 -610 -970 C -615.519 -970 -620 -965.519 -620 -960 L -620 -960 L -620 -940 C -620 -934.481 -624.481 -930 -630 -930 L -630 -930 C -635.519 -930 -640 -934.481 -640 -940 L -640 -960 L -640 -960 C -640 -960.172 -639.996 -960.344 -639.991 -960.515 Z "
                />
                <path
                  d=" M -460 -930 L -460 -900 C -460 -894.481 -464.481 -890 -470 -890 L -470 -890 C -475.519 -890 -480 -894.481 -480 -900 L -480 -930 L -508.82 -930 C -514.99 -930 -520 -934.481 -520 -940 L -520 -940 C -520 -945.519 -514.99 -950 -508.82 -950 L -431.18 -950 C -425.01 -950 -420 -945.519 -420 -940 L -420 -940 C -420 -934.481 -425.01 -930 -431.18 -930 L -460 -930 Z "
                />
                <path
                  d="M -470 -990 L -430 -990 C -424.481 -990 -420 -985.519 -420 -980 L -420 -980 C -420 -974.481 -424.481 -970 -430 -970 L -470 -970 C -475.519 -970 -480 -974.481 -480 -980 L -480 -980 C -480 -985.519 -475.519 -990 -470 -990 Z"
                />
                <path
                  d=" M -630 -910 L -610 -910 C -604.481 -910 -600 -905.519 -600 -900 L -600 -900 C -600 -894.481 -604.481 -890 -610 -890 L -630 -890 C -635.519 -890 -640 -894.481 -640 -900 L -640 -900 C -640 -905.519 -635.519 -910 -630 -910 Z "
                />
                <path
                  d=" M -515 -990 L -510 -990 C -504.481 -990 -500 -985.519 -500 -980 L -500 -980 C -500 -974.481 -504.481 -970 -510 -970 L -515 -970 C -520.519 -970 -525 -974.481 -525 -980 L -525 -980 C -525 -985.519 -520.519 -990 -515 -990 Z "
                />
                <path
                  d=" M -660 -910 L -680 -910 L -680 -980 C -680 -1007.596 -657.596 -1030 -630 -1030 L -430 -1030 C -402.404 -1030 -380 -1007.596 -380 -980 L -380 -900 C -380 -872.404 -402.404 -850 -430 -850 L -630 -850 C -657.596 -850 -680 -872.404 -680 -900 L -680 -920 L -660 -920 L -660 -900 C -660 -883.443 -646.557 -870 -630 -870 L -430 -870 C -413.443 -870 -400 -883.443 -400 -900 L -400 -980 C -400 -996.557 -413.443 -1010 -430 -1010 L -630 -1010 C -646.557 -1010 -660 -996.557 -660 -980 L -660 -910 Z "
                />
              </g>
            </svg>
          </div>
          <div class="text">
            <div class="top">monkey see</div>
            monkeytype
            <span style="color: var(--main-color)">Email Handler</span>
          </div>
        </div>
      </header>
      <main>
        <div class="preloader">
          <div class="icon">
            <i class="fas fa-fw fa-spin fa-circle-notch"></i>
          </div>
          <div class="text">‎</div>
          <div class="subText">‎</div>
        </div>
        <div class="resetPassword hidden">
          <input class="pwd" type="password" placeholder="New password" />
          <input
            class="pwd-confirm"
            type="password"
            placeholder="Confirm new password"
          />
          <div class="button">Change</div>
        </div>
      </main>
    </div>
  </body>
  <script type="module">
    import $ from "jquery";
    import {
      applyActionCode,
      verifyPasswordResetCode,
      confirmPasswordReset,
      checkActionCode,
      sendPasswordResetEmail,
      signInWithEmailAndPassword,
      getAuth,
    } from "firebase/auth";
    import { initializeApp } from "firebase/app";
    import { firebaseConfig } from "./ts/constants/firebase-config";

    const app = initializeApp(firebaseConfig);
    const Auth = getAuth(app);

    function isPasswordStrong(password) {
      const hasCapital = !!password.match(/[A-Z]/);
      const hasNumber = !!password.match(/[\d]/);
      const hasSpecial = !!password.match(
        /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/
      );
      const isLong = password.length >= 8;
      const isShort = password.length <= 64;
      return hasCapital && hasNumber && hasSpecial && isLong && isShort;
    }

    function handleVerifyEmail(actionCode, continueUrl) {
      applyActionCode(Auth, actionCode)
        .then((resp) => {
          // Email address has been verified.

          $("main .preloader .icon").html(`<i class="fas fa-fw fa-check"></i>`);
          $("main .preloader .text").text(
            `Your email address has been verified`
          );
          $("main .preloader .subText").text(`You can now close this tab`);
        })
        .catch((error) => {
          console.error(error);
          $("main .preloader .icon").html(`<i class="fas fa-fw fa-times"></i>`);
          $("main .preloader .text").text(
            `Fatal error: ${error.message}. If this issue persists, please report it.`
          );
          // Code is invalid or expired. Ask the user to verify their email address
          // again.
        });
    }

    function showResetPassword() {
      $("main .preloader").addClass("hidden");
      $("main .resetPassword").removeClass("hidden");
      $("main .resetPassword input").trigger("focus");
    }

    function hideResetPassword() {
      $("main .preloader").removeClass("hidden");
      $("main .resetPassword").addClass("hidden");
    }

    function handleResetPassword(actionCode, continueUrl) {
      // Verify the password reset code is valid.
      hideResetPassword();
      verifyPasswordResetCode(Auth, actionCode)
        .then((email) => {
          var accountEmail = email;

          var newPassword = $("main .resetPassword .pwd").val();
          var newPasswordConfirm = $("main .resetPassword .pwd-confirm").val();

          if (newPassword !== newPasswordConfirm) {
            alert("Passwords do not match");
            showResetPassword();
            return;
          }

          if (!isPasswordStrong(newPassword)) {
            alert(
              "Password must contain at least one capital letter, number, a special character and must be between 8 and 64 characters long"
            );
            showResetPassword();
            return;
          }

          // Save the new password.
          confirmPasswordReset(Auth, actionCode, newPassword)
            .then((resp) => {
              // Password reset has been confirmed and new password updated.
              $("main .preloader .icon").html(
                `<i class="fas fa-fw fa-check"></i>`
              );
              $("main .preloader .text").text(`Your password has been changed`);
              $("main .preloader .subText").text(`You can now close this tab`);

              signInWithEmailAndPassword(Auth, accountEmail, newPassword);
            })
            .catch((error) => {
              console.error(error);
              $("main .preloader .icon").html(
                `<i class="fas fa-fw fa-times"></i>`
              );
              $("main .preloader .text").text(
                `Fatal error: ${error.message}. If this issue persists, please report it.`
              );
              // Error occurred during confirmation. The code might have expired or the
              // password is too weak.
            });
        })
        .catch((error) => {
          console.error(error);
          $("main .preloader .icon").html(`<i class="fas fa-fw fa-times"></i>`);
          $("main .preloader .text").text(
            `Fatal error: ${error.message}. If this issue persists, please report it.`
          );

          // $("main .preloader .subText").text(error);

          // Invalid or expired action code. Ask user to try to reset the password
          // again.
        });
    }

    function handleRecoverEmail(auth, actionCode, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
      var restoredEmail = null;
      // Confirm the action code is valid.
      checkActionCode(Auth, actionCode)
        .then((info) => {
          // Get the restored email address.
          restoredEmail = info["data"]["email"];

          // Revert to the old email.
          return applyActionCode(Auth, actionCode);
        })
        .then(() => {
          $("main .preloader .icon").html(`<i class="fas fa-fw fa-check"></i>`);
          $("main .preloader .text").text(`Your account email was reverted.`);
          $("main .preloader .subText").text(``);

          $("main .preloader").append(`
          <br>
          In case you believe your account was compromised, please request a password reset email:
          `);
          $("main .preloader").append(`
          <br>
          <div class="button" onclick="sendPasswordReset('${restoredEmail}')">Send Password Reset Email</div>
          `);

          // Account email reverted to restoredEmail

          // TODO: Display a confirmation message to the user.

          // You might also want to give the user the option to reset their password
          // in case the account was compromised:
        })
        .catch((error) => {
          console.error(error);
          $("main .preloader .icon").html(`<i class="fas fa-fw fa-times"></i>`);
          $("main .preloader .text").text(error.message);
        });
    }

    function sendPasswordReset(email) {
      sendPasswordResetEmail(Auth, email)
        .then(() => {
          $("main .preloader .icon").html(`<i class="fas fa-fw fa-check"></i>`);
          $("main .preloader .text").text(`Password reset email sent`);
          $("main .preloader .subText").text(`Please check your inbox`);
        })
        .catch((error) => {
          console.error(error);
          $("main .preloader .icon").html(`<i class="fas fa-fw fa-times"></i>`);
          $("main .preloader .text").text(error.message);
        });
    }

    function getParameterByName(name, url = window.location.href) {
      name = name.replace(/[\[\]]/g, "\\$&");
      var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
      if (!results) return null;
      if (!results[2]) return "";
      return decodeURIComponent(results[2].replace(/\+/g, " "));
    }

    document.addEventListener(
      "DOMContentLoaded",
      () => {
        try {
          // Get the action to complete.
          var mode = getParameterByName("mode");
          // Get the one-time code from the query parameter.
          var actionCode = getParameterByName("oobCode");
          // (Optional) Get the continue URL from the query parameter if available.
          var continueUrl = getParameterByName("continueUrl");
          // (Optional) Get the language code if available.
          var lang = getParameterByName("lang") || "en";

          // Configure the Firebase SDK.
          // // This is the minimum configuration required for the API to be used.
          // var config = {
          //   'apiKey': "YOU_API_KEY" // Copy this key from the web initialization
          //                           // snippet found in the Firebase console.
          // };
          // var app = firebase.initializeApp(config);
          // var auth = firebase.auth();

          if (!mode) {
            $("main .preloader .icon").html(
              `<i class="fas fa-fw fa-times"></i>`
            );
            $("main .preloader .text").text(`Mode parameter not found`);
            return;
          }

          if (!actionCode) {
            $("main .preloader .icon").html(
              `<i class="fas fa-fw fa-times"></i>`
            );
            $("main .preloader .text").text(`Action code parameter not found`);
            return;
          }

          // Handle the user management action.
          switch (mode) {
            case "resetPassword":
              // Display reset password handler and UI.
              $("#logo .text span").text("Reset Password");
              document.title = "Reset Password | Monkeytype";
              showResetPassword();
              break;
            case "recoverEmail":
              // Display email recovery handler and UI.
              handleRecoverEmail(actionCode);
              break;
            case "verifyEmail":
              $("#logo .text span").text("Verify Email");
              document.title = "Verify Email | Monkeytype";
              // Display email verification handler and UI.
              handleVerifyEmail(actionCode, continueUrl);
              break;
            default:
              $("main .preloader .icon").html(
                `<i class="fas fa-fw fa-times"></i>`
              );
              $("main .preloader .text").text(`Invalid mode`);
              console.error("no mode found");
            // Error: invalid mode.
          }

          $("main .resetPassword .button").on("click", () => {
            handleResetPassword(actionCode, continueUrl);
          });

          $("main .resetPassword input").on("keypress", (e) => {
            if (e.key === "Enter") handleResetPassword(actionCode, continueUrl);
          });
        } catch (e) {
          $("main .preloader .icon").html(`<i class="fas fa-fw fa-times"></i>`);
          $("main .preloader .text").text(
            `Fatal error: ${e.message}. If this issue persists, please report it.`
          );
        }
      },
      false
    );

    document.querySelector("header").addEventListener("click", () => {
      window.location = "/";
    });
  </script>
</html>
